import history from 'connect-history-api-fallback'
import express from 'express'
import { createProxyMiddleware } from './fix/proxyMiddleware'

export class AppServer {
  app = express()
  _listenPromise
  _server

  constructor() {
    const DEV_URL = process.env.DEV_URL

    if (!__DEV__ || !DEV_URL) {
      this.app.use(express.static(__RENDERER_DIR__))
    }
    // .use(json())
    // .use(urlencoded({ extended: false }))
    // .use(cookieParser())

    if (__DEV__ && DEV_URL) {
      this.app.use('/', createProxyMiddleware({ target: DEV_URL, changeOrigin: true }))
    } else {
      this.app.use(history())
    }

    process.on('exit', () => this.close())
  }

  listen(port = 0, hostname = 'localhost') {
    return (
      this._listenPromise ??
      (this._listenPromise = new Promise((resolve, reject) => {
        const server = (this._server = this.app.listen(port, hostname, () => {
          const { address, port } = server.address()

          const url = `http://${address}:${port}`
          resolve(url)
          console.info(`Application is running on ${url}`)
        }))
      }))
    )
  }

  close() {
    this._server?.close()
    this._server = this._listenPromise = undefined
  }
}

export const appServer = new AppServer()
appServer.listen()
